import os
import sys
import time
import string
import pdb

sys.path.insert(0, os.path.join('..', '..', '..', '..'))


from adspygoogle.common import Utils
from adspygoogle.dfp.DfpClient import DfpClient
from adspygoogle.dfp import DfpUtils
from adspygoogle.dfp.DfpErrors import *

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# the production environment.
inventory_service = client.GetInventoryService('https://www.google.com', 'v201111')
network_service = client.GetNetworkService('https://www.google.com', 'v201111')
line_item_service = client.GetLineItemService('https://www.google.com', 'v201111')
lica_service = client.GetLineItemCreativeAssociationService('https://www.google.com', 'v201111')
pql_service = client.GetPublisherQueryLanguageService('https://www.google.com', 'v201111')
networkAdUnits = DfpUtils.GetAllEntitiesByStatementWithService(inventory_service)

ad_unit_indexer = dict((n['id'], i) for i,n in enumerate(networkAdUnits))


def main():
	argv = sys.argv
	line_item_id = argv[1]	
	site_url = argv[2]		
	preview_urls = []

	if not site_url:
		site_urls = getAdUnitDescsForLineItemId( line_item_id )
		for url in site_urls:
			for pair in getPreviewUrlForLineItemId( line_item_id, url ):
				preview_urls.append( pair )

	else:
		for pair in getPreviewUrlForLineItemId( line_item_id, site_url ):
			preview_urls.append( pair )
		
		
		
	for id_url in preview_urls:
		print id_url[0] + ': ' + id_url[1]
		
		
def getPreviewUrlForLineItemId( line_item_id, site_url ):
	creative_ids = getCreativeIdsForLineItemId( line_item_id )
	preview_urls = []
	for c_id in creative_ids:
		preview_urls.append( [ c_id, lica_service.GetPreviewUrl( line_item_id, c_id, site_url )[0] ] )
	
	return preview_urls
		
		
def getCreativeIdsForLineItemId(line_item_id):
	values = [{
	    'key': 'lineItemId',
	    'value': {
	        'xsi_type': 'NumberValue',
	        'value': line_item_id
	    }
	}]
	filter_statement = {'query': 'WHERE lineItemId = :lineItemId LIMIT 500',
	                    'values': values}

	# Get LICAs by statement.
	response = lica_service.GetLineItemCreativeAssociationsByStatement( filter_statement )
	creativeIds = []

	for r in response[0]['results']:
		if r['status'] == 'ACTIVE':
			creativeIds.append(r['creativeId'])

	return creativeIds

def getAdUnitDescForAdUnitId(adUnitId):
  desc = networkAdUnits[ad_unit_indexer[adUnitId]]['description']
  return desc


def getAdUnitDescsForLineItemId(lineItemId):
  adUnitsDesc = []
  values = [{
    'key': 'lineItemId',
    'value': {
        'xsi_type': 'NumberValue',
        'value': lineItemId
        }
   }]

  filter_statement = {'query': 'WHERE id = :lineItemId LIMIT 500',
                      'values': values}
  response = line_item_service.GetLineItemsByStatement(filter_statement)[0]
  resp = response['results'][0]['targeting']['inventoryTargeting']['targetedAdUnits']
  for line in resp:
    adUnitsDesc.append( getAdUnitDescForAdUnitId( line['adUnitId'] ) )

  return adUnitsDesc

if __name__ == '__main__':
  main()
	
	